package com.ruoyi.common.domin;

import java.io.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName DeepCloneUtils
 * @Description 对象的复制相关方法
 * @Author 张永永
 * @Date 2020-12-22 15:10
 * @Version 1.0.0.0
 **/
public class DeepCloneUtils {

    /**
     * 通过序列化的方式深表复制对象
     * @param obj 输入对象
     * @param <T>  泛型
     * @return 深表复制后的对象
     */
    @SuppressWarnings("unchecked")
    public static  <T>  T clone(T obj){
        T clonedObj = null;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            objectOutputStream.close();

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            clonedObj = (T) objectInputStream.readObject();
            objectInputStream.close();

        }catch (Exception e){
            e.printStackTrace();
        }
        return clonedObj;
    }
}
